package com.gexiaobao.pigeon.ui.auction.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.model.param.ReSendSMSParam
import com.gexiaobao.pigeon.app.network.HttpUtil
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentAuctionOrderBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.activity.TestInputActivity
import com.gexiaobao.pigeon.ui.adapter.AdapterAuctionOrder
import com.gexiaobao.pigeon.ui.auction.ActivityAuctionPigeonDetail
import com.gexiaobao.pigeon.ui.dialog.PayPassDialog
import com.gexiaobao.pigeon.ui.dialog.PayPassView
import com.gexiaobao.pigeon.ui.dialog.RxDialogApplyPayAuction
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.dialog.RxPayDialog
import com.gexiaobao.pigeon.viewmodel.AuctionViewModel
import com.google.gson.Gson
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.util.startActivity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONException
import org.json.JSONObject

/**
 * @Author      : hxw
 * @Date        : 2024/11/27 9:19
 * @Describe    : 拍卖-我的订单
 */
class FragmentAuctionOrder : BaseFragment<AuctionViewModel, FragmentAuctionOrderBinding>() {

    private var isUseMargin: Boolean = false
    private var marginBalance: Double = 0.0
    private var orderTotalMoney: Double = 0.0
    private var mOrderId: Int = 0
    private lateinit var loadsir: LoadService<Any>
    private val mAdapter: AdapterAuctionOrder by lazy { AdapterAuctionOrder(arrayListOf()) }
    private var mOrderStatus = ""//状态 1-未设置运费 2-已设置运费待付款 3-已付款 4-已发货 5-已收货 6-已评价 7-售后中 8-已退款 9-已退货 10-已退货退款 11-已付款未付保证金
    private var payPassDialog: PayPassDialog? = null
    private var payDialog: RxPayDialog? = null

    override fun initView(savedInstanceState: Bundle?) {
        mOrderStatus = requireArguments().getString("orderStatus").toString()
        /** 状态页配置 */
        loadsir = loadServiceInit(mDatabind.includeList.swipeRefreshLayout) {
            /** 点击重试时触发的操作 */
            onRefresh(isRefresh = true)
        }
        onRefresh(isRefresh = true)
        mDatabind.includeList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 12f)))
            it.initFooter {
                onRefresh(isRefresh = false)
            }
        }

        mDatabind.includeList.swipeRefreshLayout.init {
            onRefresh(isRefresh = true)
        }

        mAdapter.addChildClickViewIds(R.id.tvOrderAuctionPay, R.id.tvAllOrderItemPhone, R.id.tvOnLineChat)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tvOnLineChat -> chatLogin(mAdapter.data[position].orgUserId)
                R.id.tvAllOrderItemPhone -> showCallPhoneDialog((mAdapter.data[position].phoneNo))
                R.id.tvOrderAuctionPay -> {
                    orderTotalMoney = mAdapter.data[position].finalPrice.toDouble()
                    mOrderId = mAdapter.data[position].orderId
                    when (mAdapter.data[position].orderStatus) {
                        2 -> getMarginBalance()
                        3, 4 -> receiveAuctionOrder(mAdapter.data[position].orderId)
                    }
                }
            }
        }

        mAdapter.setOnItemClickListener { _, _, _ ->
            //订单详情暂无接口
//            startActivity<ActivityAuctionOrderDetail>("auctionId" to mAdapter.data[position].auctionId)
        }

        mAdapter.setOnOrderGoodsClickListener(object : AdapterAuctionOrder.OnOrderGoodsClickListener {
            override fun onItemClick(goodId: Int, coverImage: String) {
                startActivity<ActivityAuctionPigeonDetail>("goodId" to goodId, "type" to 1)
            }
        })
    }

    private fun receiveAuctionOrder(orderId: Int) {
        val dialog = RxDialogDefault(context)
        dialog.setTitle("确定已收到此次拍得的商品?")
        dialog.setSureListener {
            dialog.dismiss()
            val map = mapOf("auctionOrderId" to orderId)
            val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
            showLoading(getString(R.string.loading))
            mViewModel.receiveAuctionOrder(body)
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun getMarginBalance() {
        showLoading(getString(R.string.loading))
        mViewModel.getTotalFreezeMoney()
    }

    private fun showApplyPayDialog(balance: String) {
        val dialog = RxDialogApplyPayAuction(context)
        dialog.setMarginBalance(balance)
        dialog.setSureListener {
            isUseMargin = dialog.getIsUseMargin()
            showLoading(getString(R.string.loading))
            mViewModel.getPayInfoAndApplyPay(isUseMargin, mOrderId)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showCallPhoneDialog(phone: String) {
        val dialog = RxDialogDefault(context)
        dialog.setTitle("确定向以下手机号拨打电话?")
        dialog.setContent(phone)
        dialog.setSureListener {
            requestPermission(phone)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun onRefresh(isRefresh: Boolean) {
        if (isRefresh)
            loadsir.showLoading()
        mViewModel.getAuctionOrderListApp(isRefresh, mOrderStatus)
    }

    private fun paySuccess() {
        payDialog!!.showBottomBtnSingle()
        payDialog?.successAnimDialog()
        payDialog?.setDialogContent(getString(R.string.payment_success))
    }

    private fun payError() {
        payDialog!!.showBottomBtnSingle()
        payDialog?.failAnimDialog()
        payDialog?.setDialogContent(getString(R.string.payment_failure))
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 确认收货 */
        mViewModel.receiveOrderResult.observe(this) {
            dismissLoading()
            RxToast.success("已确认收货")
            onRefresh(isRefresh = true)
        }
        /** 确认支付 */
        mViewModel.payAuctionResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                onRefresh(isRefresh = true)
                eventViewModel.toRefreshData.value = true
                paySuccess()
            } else {
                payError()
                RxToast.error(it.errorMsg)
            }
            payPassDialog?.dismiss()
        }
        /** 重新发送验证码  */
        mViewModel.reSendSMSResult.observe(this) {
            dismissLoading()
            if (!it.isSuccess) {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 申请支付 */
        mViewModel.applyOrderResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (marginBalance >= orderTotalMoney && isUseMargin) {
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val map = mapOf("auctionOrderId" to mOrderId, "orderId" to it.orderId, "verificationCode" to "")
                    val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
                    mViewModel.payAuctionOrder(body)
                    /** 确认支付 */
                }, lifecycleScope)
            } else {
                showPayDialog(it.orderId)
            }
        }
        /** 获取保证金信息 */
        mViewModel.freezeMoneyResult.observe(viewLifecycleOwner) {
            marginBalance = it.remainMoney
            showApplyPayDialog(marginBalance.toString())
        }
        /** 获取app订单列表 */
        mViewModel.auctionOrderListResult.observe(viewLifecycleOwner) {
            loadListData(it, mAdapter, loadsir, mDatabind.includeList.swipeRecyclerView, mDatabind.includeList.swipeRefreshLayout)
        }
    }

    private fun showPayDialog(orderId: Int) {
        payPassDialog = PayPassDialog(context)
        val textWatcherListener = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            @SuppressLint("SetTextI18n")
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    val str = "" + s
                    if (str.length == 6) {
                        if (payPassDialog != null) {
                            val split = str.trim().replace(" ", "").split("")
                            if (split.size == 6) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[0]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[5]
                                payPassDialog!!.payViewPass.strPass = str
                            } else if (split.size == 8) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[5]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[6]
                                payPassDialog!!.payViewPass.strPass = str
                            }
                        }
                    }
                }
            }
        }
        payPassDialog!!.payViewPass.mTvPass[0].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[1].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[2].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[3].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[4].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[5].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.setPayClickListener(object : PayPassView.OnPayClickListener {
            override fun onPaySubmit() {}

            override fun onPayClose() {
                RxToast.showToast("关闭支付")
                payPassDialog!!.dismiss()
            }

            override fun onPayForget() {
                reSendSMS(orderId)
            }

            override fun onPassFinish(verifyCode: String?) {
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val map = mapOf("auctionOrderId" to mOrderId, "orderId" to orderId, "verificationCode" to verifyCode)
                    val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
                    mViewModel.payAuctionOrder(body)
                    /** 确认支付 */
                }, lifecycleScope)
            }
        })
    }

    private fun reSendSMS(orderId: Int) {
        val body = ReSendSMSParam(orderId = orderId)
        mViewModel.reSendSMS(body)
    }

    private fun showPayAnimDialog() {
        payDialog = RxPayDialog(context)
        payDialog!!.loadingDialog()
        payDialog!!.setCancelListener {
            payDialog!!.dismiss()
        }
        payDialog!!.setCanceledOnTouchOutside(false)
        payDialog!!.setFullScreenWidth()
        payDialog!!.show()
    }

    private fun chatLogin(orgUserId: Int) {
        val uid = KvUtils.decodeString(Constant.USERID)
        val token = CacheUtil.getToken()
        if (!TextUtils.isEmpty(uid) && !TextUtils.isEmpty(token)) {
            val jsonObject = JSONObject()
            try {
                jsonObject.put("uid", uid)
                jsonObject.put("token", token)
                jsonObject.put("device_flag", 0)
                jsonObject.put("device_level", 1)
            } catch (e: JSONException) {
                throw RuntimeException(e)
            }
            Thread {
                HttpUtil.getInstance().post("/user/token", jsonObject) { code, _ ->
                    if (code == 200) {
                        startActivity<TestInputActivity>("channelId" to orgUserId.toString(), "token" to token, "uid" to uid)
                    } else {
                        runOnUiThread { RxToast.showToast("登录失败【$code】") }
                    }
                }
            }.start()
        }
    }

    private fun requestPermission(orderAuctionPhone: String) {
        XXPermissions.with(this)
            .permission(Permission.CALL_PHONE)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    val intent = Intent(Intent.ACTION_CALL)
                    val data = Uri.parse("tel:$orderAuctionPhone")
                    intent.setData(data)
                    startActivity(intent)
                } else {
                    RxToast.showToast("权限不足，请手动开启权限后重试")
                }
            }
    }

    companion object {
        fun newInstance(orderStatus: String): FragmentAuctionOrder {
            val fragment = FragmentAuctionOrder()
            val bundle = Bundle()
            bundle.putString("orderStatus", orderStatus)
            fragment.arguments = bundle
            return fragment
        }
    }
}